package com.pxmeta.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pxmeta.user.entity.Rank;
import com.pxmeta.user.entity.UserRank;
import com.pxmeta.user.mapper.UserRankMapper;
import com.pxmeta.user.service.IRankService;
import com.pxmeta.user.service.IUserRankService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class UserRankServiceImpl extends ServiceImpl<UserRankMapper, UserRank> implements IUserRankService {

    private final IRankService rankService;

    @Override
    public void addNobleExp(Long userId, Integer exp) {
        UserRank userRank = this.getById(userId);
        if (userRank == null){
            userRank = new UserRank();
            userRank.setUserId(userId);
            this.save(userRank);
            userRank = this.getById(userId);
        }
        Integer currentExp = userRank.getNobleExperience();
        int finalExp = currentExp + exp;
        userRank.setNobleExperience(finalExp);

        //获取当前贵族等级
        Integer nobleRank = userRank.getNobleRank();
        Rank rank = rankService.getNobleRank(nobleRank+1);
        if (rank==null){
            nobleRank++;
            userRank.setNobleRank(nobleRank);
            this.updateById(userRank);
            return;
        }
        //升级所需要的经验值
        Integer rankExp = rank.getExp();
        if (finalExp >= rankExp){
            //升级
            nobleRank++;
        }
        userRank.setNobleRank(nobleRank);
        this.updateById(userRank);
    }

    @Override
    public void addCharmExp(Long userId, Integer exp) {
        UserRank userRank = this.getById(userId);

        if (userRank == null){
            userRank = new UserRank();
            userRank.setUserId(userId);
            this.save(userRank);
            userRank = this.getById(userId);
        }
        Integer currentExp = userRank.getCharmExperience();
        int finalExp = currentExp + exp;
        userRank.setCharmExperience(finalExp);

        //获取当前魅力等级
        Integer charmRank = userRank.getCharmRank();
        //获取下一级
        Rank rank = rankService.getCharmRank(charmRank+1);
        if (rank == null){
            charmRank++;
            userRank.setCharmRank(charmRank);
            this.updateById(userRank);
            return;
        }

        //升级所需要的经验值
        Integer rankExp = rank.getExp();
        if (finalExp >= rankExp){
            //升级
            charmRank++;
        }
        userRank.setCharmRank(charmRank);
        this.updateById(userRank);
    }

}
